<!-- 前台收银界面 -->
<%@ page language="java"  pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="model.SessionInfo"%>
<%
	String contextPath = request.getContextPath();
	SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
%>
<style>
/* 设置dailog行高  */
.datagrid-row {
height:23px;
}
/* 设置dailog字体样式  */
.datagrid-row td div{
font-size:16px;
font-height:bolder;
}
</style>
<script type="text/javascript" charset="utf-8">
var datagrid;
var setteleDialog;//结算窗口
var delayReceipt;//补打小票窗口
editRow=undefined;
	$(function() {//获得输入框焦点
		window.setTimeout(function(){
			$('#admin_cashier_searchForm input[name="foodid"]').focus();
	}, 0);
		editRow=undefined;//标志是否处于编辑转态
		datagrid=$('#admin_cashier_datagrid').datagrid({//datagrid设置
			url : ' ',
			title : '',
			iconCls : 'icon-save',
			pagination : true,//是否显示翻页条
			pageSize : 5,
			pageList : [ 5, 10, 15, 20 ],//每页显示数量
			fit : true,
			fitColumns : true,
			nowrap : false,//是否禁止自动换行
			border : false,//是否显示边框
			idField : 'id',
			checkOnSelect:true,//设为false只有点击checkbox行才被选中
			selectOnCheck:true,//设为false点击行checkbox不会被选中
                columns : [ [ {
    				field : 'id',
    				title : '编号',
    				width : 100,
    				checkbox:true
    			}, {
    				field : 'code',
    				title : '商品条形码编码',
    				width : 100
    			}, {
    				field : 'name',
    				title : '商品名称',
    				width : 100
    			}, {
    				field : 'amount',
    				title : '数量',
    				width : 100,
    				editor:{
    					type:'numberbox',
    					options:{
    						 required:true,
    						 missingMessage:'该项必须输入正整数',
    						}
    			           }
    			}, {
    				field : 'unit',
    				title : '商品单位',
    				width : 100
    			},{
    				field : 'price',
    				title : '商品单价',
    				width : 100,
    				sortable:true
    			},{
    				field : 'nprice',
    				title : '金额',
    				width : 100,
    				sortable:true,
    				formatter :function(value,row,index){
    					return value.toFixed(2);
    				}
    			} ] ],
    			toolbar:[{
					text:'删除行',
					iconCls:'icon-remove',
					handler:function(){
						var row=$('#admin_cashier_datagrid').datagrid('getSelected');
						if(row!=null){
						var rowIndex=$('#admin_cashier_datagrid').datagrid('getRowIndex',row);
						$('#admin_cashier_datagrid').datagrid('deleteRow',rowIndex);
						$('#admin_cashier_datagrid').datagrid('load');
						calculateTotalPrice();
    			    	calculateQuantity();
    			    	receivable();
    			    	window.setTimeout(function(){
    						$('#admin_cashier_searchForm input[name="foodid"]').focus();
    				    }, 0);
					}else{
						$.messager.alert('警告','请选择要删除的记录!','warning');
						window.setTimeout(function(){
							$('#admin_cashier_searchForm input[name="foodid"]').focus();
					    }, 0);
					}
				  }
			    },'-',{
    				text:'修改',
    				iconCls:'icon-edit',
    				handler:function(){
    					var rows=$('#admin_cashier_datagrid').datagrid('getChecked');
    					if(rows.length==1){
    						changeEditorEditRow();
    						if(editRow!=undefined){
    							$('#admin_cashier_datagrid').datagrid('endEdit',editRow);
    						}
    						if(editRow==undefined){
    							var index= $('#admin_cashier_datagrid').datagrid('getRowIndex',rows[0]);
    						    $('#admin_cashier_datagrid').datagrid('beginEdit',index);
    						    editRow=index;
    						    $('#admin_cashier_datagrid').datagrid('unselectAll');
    						}
    					}
    					if(rows.length>1){
    						$.messager.alert('警告','同一时间只能修改一条记录!','warning');
    					}if(rows.length<1){
    						$.messager.alert('警告','请选择要修改的记录!','warning');
    					}
    				}
    			},'-',{
    					text:'保存',
    					iconCls:'icon-save',
    					handler:function(){
    						$('#admin_cashier_datagrid').datagrid('endEdit',editRow);
    					}
    			},'-',{
    				text:'取消编辑',
    				iconCls:'icon-undo',
    				handler:function(){
    					editRow=undefined;
    					$('#admin_cashier_datagrid').datagrid('rejectChanges');
    					$('#admin_cashier_datagrid').datagrid('unselectAll');
    					calculateTotalPrice();
    			    	calculateQuantity();
    			    	receivable();
    				}
    			},'-',{
    				text:'清空单据',
    				iconCls:'icon-undo',
    				handler:function(){
    					$('#admin_cashier_datagrid').datagrid('loadData',{total:0,rows:[]});
    					$('#admin_cashier_datagrid').datagrid('unselectAll');
						$('#cashier_sum input[name="totalsum"]').attr('value',"");
						$('#cashier_sum input[name="totalnum"]').attr('value',"");
						$('#cashier_sum input[name="receivable"]').attr('value',"");
						window.setTimeout(function(){
							$('#admin_cashier_searchForm input[name="foodid"]').focus();
					    }, 0);
    				}
    			},'-',{
    				text:'提取单据',
    				iconCls:'icon-print',
    				handler:function(){
    					getMemory();
    				}
    			},'-',{
    				text:'挂账',
    				iconCls:'icon-filter',
    				handler:function(){
                        memory();
    				}
    			},'-'],
    			onAfterEdit:function(rowIndex,rowData,changes){
    				var updated=$('#admin_cashier_datagrid').datagrid('getChanges','updated');
    				if (updated.length < 1) {
    					editRow = undefined;
    					$('#admin_cashier_datagrid').datagrid('unselectAll');
    					return;
    				}
    				if(updated.length>0){
    					$('#admin_cashier_datagrid').datagrid('updateRow',{
  	    				  index:rowIndex,
  	    				  row :{
  	    					  amount:rowData.amount,
  	    			          nprice:rowData.amount*rowData.price
  	    				  }
  	    			  });
    				  $('#admin_cashier_datagrid').datagrid('unselectAll');
    				  editRow = undefined;
    				  calculateQuantity();
  	    			  calculateTotalPrice();
  			    	  receivable();
  			    	  window.setTimeout(function(){
  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
  				      }, 0);
    				}
    			},
    			onDblClickRow:function(rowIndex,rowData){
    				changeEditorEditRow();
    				if(editRow!=undefined){
    					$('#admin_cashier_datagrid').datagrid('endEdit',editRow);
    					$('#admin_cashier_datagrid').datagrid('unselectAll');
    					editRow==undefined;
    				}
    				if(editRow==undefined){
    				    $('#admin_cashier_datagrid').datagrid('beginEdit',rowIndex);
    				    editRow=rowIndex;
    				    $('#admin_cashier_datagrid').datagrid('unselectAll');
    				}
    			} 
    		});
		changeEditorEditRow=function(){ //开启行编辑转态时移除某些列的可编辑状态
			$('#admin_cashier_datagrid').datagrid('removeEditor',['code','name','unit','price','nprice']);
		};
		$('#admin_cashier_searchForm').form({ //输入商品编号动态显示商品信息列表并计算总额
		      url : '${pageContext.request.contextPath}/cashierAction!show.action',
		      success:function(r){
		      var obj=jQuery.parseJSON(r);
		      if(obj.rows.length>0){
		    	  var tid=$('#cashier_head input[name="tid"]').val();
			      if(tid==null||tid==""||tid==undefined){
			      getOrder(); //获取销售单号
			      }
		    	  if(isExist(obj)){
		    		  
		    	  }else{
		    	    $('#admin_cashier_datagrid').datagrid('insertRow',{
				       index:0,
				       row:{
				    	   id:obj.rows[0].id,
				    	   code:obj.rows[0].code,
				    	   name:obj.rows[0].name,
				    	   amount:obj.rows[0].amount,
				    	   unit:obj.rows[0].unit,
				    	   price:obj.rows[0].price,
				    	   nprice:obj.rows[0].nprice
				    	}
				  });
		    	  } 
                  calculateQuantity(); //计算总数量
	    		  calculateTotalPrice(); //计算总额
			      receivable(); //计算应收金额
		    	  $('#admin_cashier_searchForm input[name="foodid"]').val('');
		    	  $('#admin_cashier_datagrid').datagrid('acceptChanges');
				  $('#admin_cashier_datagrid').datagrid('load');
				  $('#admin_cashier_datagrid').datagrid('unselectAll');
		      }else{
		    	  $.messager.show({
				    	title:'警告',
				    	msg:'没有查到该商品!'
				    	});
		    	  $('#admin_cashier_searchForm input[name="foodid"]').val('');
		      }
		}
	});
		calculateTotalPrice=function(){ //计算总额
			var rows=$('#admin_cashier_datagrid').datagrid('getRows');
			var result=0;
			for(var i=0;i<rows.length;i++){
				result+=rows[i]['nprice'];
				$('#cashier_sum input[name="totalsum"]').attr('value',result.toFixed(2));//保留两位小数
			}
		};
		calculateQuantity=function(){ //计算总数量
			var rows=$('#admin_cashier_datagrid').datagrid('getRows');
			var result=0;
			for(var i=0;i<rows.length;i++){
				result+=parseInt(rows[i]['amount']);
				$('#cashier_sum input[name="totalnum"]').attr('value',result);
			}
		};
		receivable=function(){ //计算应收金额
			var totalsum=$('#cashier_sum input[name="totalsum"]').val();
			 var discount=$('#cashier_sum input[name="discount"]').val(); 
			 if(discount.length==0||discount==undefined||discount==null){
				discount=1; 
			 }
			var receivable=totalsum*discount;
			$('#cashier_sum input[name="receivable"]').attr('value',receivable.toFixed(2));
		};
		function isExist(obj){ //判断datagrid中是否有该商品,有则再次输入该商品编号时只更新该商品行数量+1
			 var rows=$('#admin_cashier_datagrid').datagrid('getRows');
	    	  for(var i=0;i<rows.length;i++){
	    		  if(rows[i]['code']==obj.rows[0].code){
	    			  rows[i]['amount']+=1;
	    			  $('#admin_cashier_datagrid').datagrid('updateRow',{
	    				  index:i,
	    				  row :{
	    					  amount:rows[i]['amount'],
	    			          nprice:rows[i]['amount']*rows[i]['price']
	    				  }
	    			  });
	    			  $('#admin_cashier_datagrid').datagrid('load');
					  $('#admin_cashier_datagrid').datagrid('unselectAll');
	    			  return true;
	    		  }
	    	   }
		}
		add=function(){ //功能键数量+1
			var row=$('#admin_cashier_datagrid').datagrid('getSelected');
			if(row!=null){
	    			  var quantity=parseInt(row.amount); //转为int格式
	    			  quantity+=1;
	    			  var rowIndex = $('#admin_cashier_datagrid').datagrid('getRowIndex', row);
	    			  $('#admin_cashier_datagrid').datagrid('updateRow',{
	    				  index:rowIndex,
	    				  row :{
	    					  amount:quantity,
	    			          nprice:quantity*row.price
	    				  }
	    			  });
	    			  calculateQuantity();
  	    			  calculateTotalPrice();
  			    	  receivable();
  			    	  window.setTimeout(function(){
  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
  				      }, 0);
			}else{
				 $.messager.alert('警告','请选择商品!','error');
			}
		};
		del=function(){ //功能键数量-1
			var row=$('#admin_cashier_datagrid').datagrid('getSelected');
			var rowIndex = $('#admin_cashier_datagrid').datagrid('getRowIndex', row);
			if(row!=null){
				var quantity=parseInt(row.amount);
  			    quantity-=1;
	    			  if(quantity>0){
	    			  $('#admin_cashier_datagrid').datagrid('updateRow',{
	    				  index:rowIndex,
	    				  row :{
	    					  amount:quantity,
	    			          nprice:quantity*row.price
	    				  }
	    			  });
	    			  calculateQuantity();
  	    			  calculateTotalPrice();
  			    	  receivable();
  			    	  window.setTimeout(function(){
  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
  				      }, 0);
	    		}else{
	    				  $.messager.alert('警告','商品数量至少为1!','warning');
	    				  quantity+=1;
	    			  }
			}else{
				 $.messager.alert('警告','请选择商品!','error');
			}
		};
		memory=function(){ //进行挂账
			var rows=$('#admin_cashier_datagrid').datagrid('getRows');
		    if(rows.length>0){
		    	var p = parent.dialog({
					title : '挂账',
					href : '${pageContext.request.contextPath}/admin/gz.jsp',
					width : 350,
					height : 250,
					buttons : [ {
						text : '确认挂账',
						iconCls :'icon-ok',
						handler : function() {
							var f = p.find('form');
							f.form('submit', {
								url : '${pageContext.request.contextPath}/receiptAction!save.action',
								success : function(d) {
									var json = $.parseJSON(d);
									if (json.success) {
									shopList();
									$('#admin_cashier_datagrid').datagrid('loadData',{total:0,rows:[]});
									$('#cashier_head').form('load',{tid:'',cardid:'',name:'',integration:''});
									$('#cashier_sum input[name="totalsum"]').attr('value',"");
									$('#cashier_sum input[name="totalnum"]').attr('value',"");
									$('#cashier_sum input[name="discount"]').attr('value',"");
									$('#cashier_sum input[name="receivable"]').attr('value',"");
									p.dialog('close');
									}
									parent.messagerShow({
										msg : '挂账成功!',
										title : '提示'
									});
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								    }, 0);
								}
							});
						}
					} ,{
						text : '取消',
						iconCls :'icon-no',
						handler : function() {
							p.dialog('close');
							window.setTimeout(function(){
								$('#admin_cashier_searchForm input[name="foodid"]').focus();
						    }, 0);
						}
					}],
					onLoad : function() {
						var f = p.find('form');
						var tid=$('#cashier_head input[name="tid"]').val();
						var vip=$('#cashier_head input[name="name"]').val();
						var cashier=$('#cashier_head input[name="cashier"]').val();
						var totalprice=$('#cashier_sum input[name="receivable"]').val();
						f.form('load', {
							tid :tid,
							vip : vip,
							cashier : cashier,
							totalprice : totalprice,
						});
					}			    
				});
		    }else{
		    	$.messager.alert('警告','没有销售信息,不能进行挂账!','error');
		    }
		};
		getMemory=function() { //弹出未支付订单信息,选择后提取单据
			var p = parent.dialog({
				title : '提取单据',
				href : '${pageContext.request.contextPath}/layout/tqdj.jsp',
				width : 775,
				height : 400,
				buttons : [ {
					text : '提取',
					iconCls :'icon-ok',
					handler : function() {
						var tid=$('#cashier_head input[name="tid"]').val();
						var rows=$('#layout_tqdj_datagrid').datagrid('getSelections');
						if(rows.length==1){
							var discount=rows[0].discount;
							var saleid=rows[0].tid;
								if(tid!=saleid){ //判断是否重复提取单据
						        insertMemory();
						        $('#cashier_head').form('load',{
							          tid : rows[0].tid,
							          cardid:rows[0].cardid,
							          name:rows[0].vip,
							          integration:rows[0].integration
						      });
						$('#cashier_sum input[name="discount"]').attr('value',discount);
						p.dialog('close');
						window.setTimeout(function(){
	  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
	  				    }, 0);
						  }else{
							 $.messager.alert('警告','不可重复提取单据!','error');
								}
					}
					if(rows.length<1){
						     $.messager.alert('警告','请选择要提取的单据!','warning');
					    }
					if(rows.length>1){
						     $.messager.alert('警告','同一时间只能提取一条记录!','warning');
					    }
					}
				    
				},{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
									p.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								    }, 0);
								}
				} ]
			    
			});
		};
		insertMemory=function(){ //将提取的单据的内容填充进admin_cashier_datagrid中
			var rows=$('#layout_tqdj_datagrid').datagrid('getSelections');
			var tid=rows[0].tid;
			$.ajax({
				type:'POST',
				url:'${pageContext.request.contextPath}/shopListAction!show.action',
				data:{
					tid : tid
				},
				dataType:'json',
				success :function(r){
						      if(r.rows.length>0){
						    	  for(var i=0;i<r.rows.length;i++){
						    		  $('#admin_cashier_datagrid').datagrid('insertRow',{
									       index:i,
									       row:{
									    	   id:r.rows[i].id,
									    	   code:r.rows[i].code,
									    	   name:r.rows[i].name,
									    	   amount:r.rows[i].amount,
									    	   unit:r.rows[i].unit,
									    	   price:r.rows[i].prices,
									    	   nprice:r.rows[i].price
									    	}
									  });
						    	  }
						    	  } 
				                  calculateQuantity();//计算总数量
					    		  calculateTotalPrice();//计算总额
							      receivable();//计算应收金额
						    	  $('#admin_cashier_searchForm input[name="foodid"]').val('');
						    	  $('#admin_cashier_datagrid').datagrid('acceptChanges');
								  $('#admin_cashier_datagrid').datagrid('load');
								  $('#admin_cashier_datagrid').datagrid('unselectAll');
				}
			});
		};
		getOrder=function(){ //得到销售单号
			$.ajax({
				type:'POST',
				url:'${pageContext.request.contextPath}/cashierAction!getOrderId.action',
				dataType:'json',
				success :function(r){
					if(r&&r.success){
						$('#cashier_head').form('load',{
							tid:r.message
						});
					}
				}
			});
		};
		getPaymentId=function(){ //得到支付单号
			$.ajax({
				type:'POST',
				url:'${pageContext.request.contextPath}/cashierAction!getOrderId.action',
				dataType:'json',
				success :function(r){
					if(r&&r.success){
						$('#settleForm input[name="pid"]').attr('value',r.message);
					}
				}
			});
		};
		shopList=function(){ //将顾客一次消费信息传至后台保存至数据库
			var rows=$('#admin_cashier_datagrid').datagrid('getRows');
			var discount=$('#cashier_sum input[name="discount"]').val();
			if(discount.length==0||discount==undefined||discount==null){
					discount=1; 
			}
	    	  if(rows.length>0){
	    		  var tid=$('#settleForm input[name="tid"]').val();
	    		  var codes=[]; //数组存储
	    		  var amounts=[];
	    		  var nprices=[];
	    		  for(var i=0;i<rows.length;i++){
	    			  codes.push(rows[i].code);
	    			  amounts.push(rows[i].amount);
	    			  nprices.push(rows[i].nprice*discount);
	    		     }
	    			$.ajax({
							url:'${pageContext.request.contextPath}/shopListAction!save.action',
							data:{
								tid:tid,
								codes:codes.join(','),//用","分割
								amounts:amounts.join(','),
								nprices:nprices.join(',')
								},
							dataType:'json',
							success:function(r){
								if(r&&r.success){
								}else{					
							  }
							}
						});
	    	  }
		};
		payment=function(){ //对默认的一次或选择其中一次销售进行支付
			var tid=$('#settleForm input[name="tid"]').val();
			var pid=$('#settleForm input[name="pid"]').val();
			var vip=$('#settleForm input[name="vip"]').val();
			var method=$('#settleForm input[name="method"]').val();
			var totalprice=$('#settleForm input[name="totalprice"]').val();
			var collection=$('#settleForm input[name="collection"]').val();
			var changes=$('#settleForm input[name="changes"]').val();
			$.ajax({
				url:'${pageContext.request.contextPath}/paymentAction!save.action',
				data:{
					tid:tid,
					pid:pid,
					vip:vip,
					method:method,
					totalprice:totalprice,
					collection:collection,
					changes:changes
					},
				dataType:'json',
				success :function(r){
					if(r&&r.success){
						$.messager.confirm("请确认","您需要打印小票吗?",function(b){
							if(b){
								printReceipt();
							}else{
								$('#admin_cashier_datagrid').datagrid('loadData',{total:0,rows:[]});
								$('#cashier_head').form('load',{tid:'',cardid:'',name:'',integration:''});
								$('#cashier_sum input[name="totalsum"]').attr('value',"");
								$('#cashier_sum input[name="totalnum"]').attr('value',"");
								$('#cashier_sum input[name="discount"]').attr('value',"");
								$('#cashier_sum input[name="receivable"]').attr('value',"");
								setteleDialog.dialog('close');//关闭结算窗口
								window.setTimeout(function(){
									$('#admin_cashier_searchForm input[name="foodid"]').focus();
							    }, 0);
							}
						});
					}
				}
			});
		};
		inventory=function(){ //修改商品库存
			var rows=$('#admin_cashier_datagrid').datagrid('getRows');
	    	  if(rows.length>0){
	    		  var codes=[]; //数组存储
	    		  var amounts=[];
	    		  for(var i=0;i<rows.length;i++){
	    			  codes.push(rows[i].code);
	    			  amounts.push(rows[i].amount);
	    		     }
	    			$.ajax({
							url:'${pageContext.request.contextPath}/shopListAction!updateInventory.action',
							data:{
								codes:codes.join(','),//用","分割
								amounts:amounts.join(','),
								},
							dataType:'json',
							success:function(r){
								if(r&&r.success){
								
								}else{					
							  }
							}
						});
	    	  }
		};
		checkout=function(){ //对结算方法的一些控制
			var totalprice=$('#settleForm input[name="totalprice"]').val();
			$('#settleForm input[name="changes"]').attr('value',"");
			$('#settleForm input[name="collection"]').keyup(function(event){
				var collection=$('#settleForm input[name="collection"]').val();
				var changes=collection-totalprice;
				if(changes<0){
					$('#settleForm input[name="changes"]').attr('value',"");//为负数时不显示
				}else{
					$('#settleForm input[name="changes"]').attr('value',changes.toFixed(2));
				}
			});
		};
		settleFun=function(){ //结算方法
			setteleDialog= parent.dialog({
				title : '结算',
				href : '${pageContext.request.contextPath}/admin/settle.jsp',
				width : 350,
				height : 450,
				buttons : [ {
					text : '结算',
					iconCls :'icon-ok',
					handler : function() {
						var f = setteleDialog.find('form');
						f.form('submit', {
							url : '${pageContext.request.contextPath}/receiptAction!save.action',
							success : function(d) {
								var json = $.parseJSON(d);
								if (json.success) {
								shopList();
								payment();
								inventory();
								}
								parent.messagerShow({
									msg : json.msg,
									title : '提示'
								});
							}
						});
					}
				} ,{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
						setteleDialog.dialog('close');
						window.setTimeout(function(){
							$('#admin_cashier_searchForm input[name="foodid"]').focus();
					}, 0);
					}
				}],
				onLoad : function() {
					var f = setteleDialog.find('form');
					var tid=$('#cashier_head input[name="tid"]').val();
					var vip=$('#cashier_head input[name="name"]').val();
					var cashier=$('#cashier_head input[name="cashier"]').val();
					var totalprice=$('#cashier_sum input[name="receivable"]').val();
					var discount=$('#cashier_sum input[name="discount"]').val();
					getPaymentId();//获取支付单号
					f.form('load', {
						tid : tid,
						vip : vip,
						cashier : cashier,
						totalprice : totalprice,
						discount : discount
					});
					checkout();
				}			    
			});
		};
		printReceipt=function(){ //打印小票(支付完成立即打印)
			var p = parent.dialog({
				title : '小票',
				width : 400,
				height: 'auto',
				top :60,
				href : '${pageContext.request.contextPath}/admin/receipt.jsp',
				buttons : [{
					text : '确定',
					iconCls :'icon-ok',
					handler : function() {
						$('#admin_cashier_datagrid').datagrid('loadData',{total:0,rows:[]});
						$('#cashier_head').form('load',{tid:'',cardid:'',name:'',integration:''});
						$('#cashier_sum input[name="totalsum"]').attr('value',"");
						$('#cashier_sum input[name="totalnum"]').attr('value',"");
						$('#cashier_sum input[name="discount"]').attr('value',"");
						$('#cashier_sum input[name="receivable"]').attr('value',"");
						p.dialog('close');
						setteleDialog.dialog('close'); //关闭结算窗口
						window.setTimeout(function(){
								$('#admin_cashier_searchForm input[name="foodid"]').focus();
							}, 0);
						}
				} ],
				onLoad : function() {
					appendReceiptTable();
				}	
			});
		};
		appendReceiptTable=function(){ //填充admin_receipt_dialog数据
			var rows = $('#admin_cashier_datagrid').datagrid('getRows');
			$('#receipt_table').append('<tr><th>编号</th><th></th>名称<th>单价</th><th>数量</th><th>金额</th></tr>');
			for (var i = 0; i < rows.length; i++) {
				 var tableRow = '<tr>' +
	             '<td>' + rows[i]['code'] + '</td>' +
	             '<td colspan="3">' + rows[i]['name'] + '</td>' + '</tr>' +
	             '<tr>' + 
	             '<td>' + '</td>' + '<td>' + '</td>' +
	             '<td>' + rows[i]['price'].toFixed(2) + '</td>' +
	             '<td>' + rows[i]['amount'] + '</td>' +
	             '<td>' + rows[i]['nprice'].toFixed(2) + '</td>' +
	             '</tr>';
				 $('#receipt_table').find('tr').css('display','table-row');
				 $('#receipt_table').append(tableRow);				
	        }
			/* 填充销售信息,包括销售单号、收银员、会员、折扣、商品总数量、商品总额、应收金额 */
			$('#r_paymentId').html($('#cashier_head input[name="tid"]').val());
			$('#r_cashier').html($('#cashier_head input[name="cashier"]').val());
			$('#r_discount').html($('#cashier_sum input[name="discount"]').val());
			$('#r_vip').html($('#cashier_head input[name="cardid"]').val());
			$('#r_amount').html($('#cashier_sum input[name="totalnum"]').val());
			$('#r_totalprice').html(parseFloat($('#cashier_sum input[name="totalsum"]').val()).toFixed(2));
			$('#r_receivable').html(parseFloat($('#cashier_sum input[name="receivable"]').val()).toFixed(2));
			if($('#cashier_head input[name="name"]').val()!=""){ //如果有会员信息,填充更新后积分
				$('#r_integration').html(parseFloat(parseFloat($('#cashier_head input[name="integration"]').val())+parseFloat($('#cashier_sum input[name="receivable"]').val())).toFixed(2));//积分
			}
			/* 填充支付信息,包括收款、找零、支付日期 */
			$('#r_collection').html(parseFloat($('#settleForm input[name="collection"]').val()).toFixed(2));
			$('#r_changes').html(parseFloat($('#settleForm input[name="changes"]').val()).toFixed(2));
			$('#r_date').html((new Date()).toLocaleString());
		};
		searchFun=function(){ //提交查询商品
			$('#admin_cashier_searchForm').submit();
		};
		$('#admin_cashier_searchForm input').bind('keypress',function(event){
			if(event.keyCode=='39'){
				if($('#admin_cashier_searchForm input[name="foodid"]').val()==""){//判断输入框是否为空
				var rows=$('#admin_cashier_datagrid').datagrid('getRows');	
				if(rows.length<1){ //判断是否有购买记录
					 $.messager.show({
					    	title:'警告',
					    	msg:'请购买商品后再结账!'
					    	});
				}else{//为空则弹出结算框
				settleFun();
				}
				}
				else{//不为空添加消费商品
				searchFun();
				}
			}
		}); 
		isGet=function(){ //判断是否已经通过查找商品增加过相同的消费商品
			 var rows=$('#admin_cashier_datagrid').datagrid('getRows');
			 var rows1=$('#layout_spcz_datagrid').datagrid('getSelections');
	    	  for(var i=0;i<rows.length;i++){
	    		  if(rows[i]['code']==rows1[0].code){
	    			  rows[i]['amount']+=1;
	    			  $('#admin_cashier_datagrid').datagrid('updateRow',{
	    				  index:i,
	    				  row :{
	    					  amount:rows[i]['amount'],
	    			          nprice:rows[i]['amount']*rows[i]['price']
	    				  }
	    			  });
	    			  $('#admin_cashier_datagrid').datagrid('load');
					  $('#admin_cashier_datagrid').datagrid('unselectAll');
	    			  return true;
	    		  }
	    	   }
		};
		 good=function() { //弹出商品查找dialog,选择商品填充进admin_cashier_datagrid中
			var p = parent.dialog({
				title : '查找商品',
				href : '${pageContext.request.contextPath}/layout/good.jsp',
				width : 775,
				height : 400,
				buttons : [ {
					text : '添加',
					iconCls :'icon-add',
					handler : function() {
						var rows=$('#layout_spcz_datagrid').datagrid('getSelections');
						if(rows.length>0){
							 if(isGet()){
								  calculateQuantity();
			  	    			  calculateTotalPrice();
			  			    	  receivable();
			  			    	  p.dialog('close');  
			  			    	  window.setTimeout(function(){
			  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
			  				      }, 0);
					    	  }else{
						for(var i=0;i<rows.length;i++){
							var tid=$('#cashier_head input[name="tid"]').val();
							if(tid==null||tid==""||tid==undefined){
							getOrder();//获取销售单号
							}
							$('#admin_cashier_datagrid').datagrid('insertRow',{
							       index:i,
							       row:{
							    	   id:rows[i].id,
							    	   code:rows[i].code,
							    	   name:rows[i].name,
							    	   amount:1,
							    	   unit:rows[i].unit,
							    	   price:rows[i].price,
							    	   nprice:rows[i].price
							    	}
							  });
							  calculateQuantity();
		  	    			  calculateTotalPrice();
		  			    	  receivable();
		  			    	  p.dialog('close');
		  			    	  window.setTimeout(function(){
		  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
		  				      }, 0);
					      }
					    }
					}else{
							$.messager.alert('警告','请选择要增加的记录!','warning');
						}
						$('#layout_spcz_datagrid').datagrid('load');
						$('#layout_spcz_datagrid').datagrid('unselectAll');
						editRow=undefined;
					}
				},{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
									p.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								    }, 0);
								}
				} ]
			    
			});
		};
		customer=function() { //弹出查找会员dialog,选择会员填充进cashier_head表单中
			var p = parent.dialog({
				title : '查找会员',
				href : '${pageContext.request.contextPath}/layout/customer.jsp',
				width : 775,
				height : 400,
				buttons : [ {
					text : '添加',
					iconCls :'icon-add',
					handler : function() {
						var rows=$('#layout_vipcz_datagrid').datagrid('getSelections');
						if(rows.length<1){
							 $.messager.alert('警告','请选择要增加的记录!','warning');
					    }
						if(rows.length==1){
						var discount=rows[0].discount;
						$('#cashier_head').form('load',{
							cardid:rows[0].cardid,
							name:rows[0].name,
							integration:rows[0].integration
						});
						$('#cashier_sum input[name="discount"]').attr('value',discount);
						receivable();
						p.dialog('close');
						window.setTimeout(function(){
	  						$('#admin_cashier_searchForm input[name="foodid"]').focus();
	  				    }, 0);
					}
						if(rows.length>1){
						     $.messager.alert('警告','同一时间只能增加一条记录!','warning');
					    }
					}
				    
				},{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
									p.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								    }, 0);
								}
				} ]
			    
			});
		};
		customer_add=function(){ //弹出新增会员dialog
			var p = parent.dialog({
				title : '添加会员',
				href : '${pageContext.request.contextPath}/layout/addcustomer.jsp',
				width : 320,
				height : 350,
				buttons : [ {
					text : '添加',
					iconCls :'icon-add',
					handler : function() {
						var f = p.find('form');
						f.form('submit', {
							url : '${pageContext.request.contextPath}/vipAction!add.action',
							success : function(d) {
								var json = $.parseJSON(d);
								if (json.success) {
									datagrid.datagrid('reload');
									p.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								}, 0);
								}
								parent.messagerShow({
									msg : json.msg,
									title : '提示'
								});
							}
						});
					}
				},{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
									p.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								}, 0);
								}
				} ]
			    
			});
		};
		outputReceipt=function(){ //补打小票
			 delayReceipt = parent.dialog({
				title : '补打小票',
				href : '${pageContext.request.contextPath}/layout/payment.jsp',
				width : 775,
				height : 400,
				buttons : [ {
					text : '打印',
					iconCls :'icon-print',
					handler : function() {
						var rows=$('#layout_payment_datagrid').datagrid('getSelections');
						if(rows.length==1){
						var tid=rows[0].tid;
						var totalprice=rows[0].totalprice;
						var collection=rows[0].collection;
						var changes=rows[0].changes;
				    	$.ajax({
								url:'${pageContext.request.contextPath}/shopListAction!outputReceipt.action',
								data:{
										tid : tid
									 },
								dataType:'json',
								success:function(r){
									if(r){
										  if(r.rows.length>0){
											   var p = parent.dialog({
											   title : '小票',
											   width : 400,
											   height: 'auto',
											   top :60,
											   href : '${pageContext.request.contextPath}/admin/receipt.jsp',
											   buttons : [{
															text : '确定',
															iconCls :'icon-ok',
															handler : function() {
															p.dialog('close');
															delayReceipt.dialog('close');
															window.setTimeout(function(){
																$('#admin_cashier_searchForm input[name="foodid"]').focus();
															}, 0);
														 }
													} ],
											  onLoad : function() {
												    var amounts=0;
												    var totalsum=0;
													$('#receipt_table').append('<tr><th>编号</th><th></th>名称<th>单价</th><th>数量</th><th>金额</th></tr>');
													for (var i = 0; i < r.rows.length; i++) {
															var code = r.rows[i].code;
														    var name = r.rows[i].name;
														    var amount = r.rows[i].amount;
														    var price = r.rows[i].prices;
														    var nprice = r.rows[i].price;
														    var vip = r.rows[i].vip;
														    var discount = r.rows[i].discount;
														    var integration = r.rows[i].integration;
														    amounts+=amount;
														    totalsum+=nprice;
															var tableRow = '<tr>' +
														      '<td>' + code + '</td>' +
														      '<td colspan="3">' + name + '</td>' + '</tr>' +
														      '<tr>' + 
														      '<td>' + '</td>' + '<td>' + '</td>' +
														      '<td>' + price + '</td>' +
														      '<td>' + amount + '</td>' +
														      '<td>' + nprice + '</td>' +
														      '</tr>';
															 $('#receipt_table').find('tr').css('display','table-row');
															 $('#receipt_table').append(tableRow);				
														 }
															/* 填充销售信息,包括销售单号、收银员、会员、折扣、商品总数量、商品总额、应收金额 */
															$('#r_paymentId').html(tid);
															$('#r_cashier').html($('#cashier_head input[name="cashier"]').val());
															$('#r_discount').html(discount);
															$('#r_vip').html(vip);
															$('#r_amount').html(amounts);
															$('#r_totalprice').html(totalsum);
															$('#r_receivable').html(totalprice);
															$('#r_integration').html(integration);//积分
															/* 填充支付信息,包括收款、找零、支付日期 */
															$('#r_collection').html(collection);
															$('#r_changes').html(parseFloat(changes).toFixed(2));
															$('#r_date').html((new Date()).toLocaleString());
													}	
												});  
										    } else{
										    	$.messager.alert('提示','该销售单购买的商品已全部退货,不能打印小票!','warning');
										    	$('#layout_payment_datagrid').datagrid('unselectAll');
										    }
									   }
								   }
							 });
						}
						if(rows.length<1){
						     $.messager.alert('警告','请选择要打印的记录!','warning');
					    }
						if(rows.length>1){
						     $.messager.alert('警告','同时只能打印一条记录!','warning');
					    }
					}			    
				},{
					text : '取消',
					iconCls :'icon-no',
					handler : function() {
						            delayReceipt.dialog('close');
									window.setTimeout(function(){
										$('#admin_cashier_searchForm input[name="foodid"]').focus();
								    }, 0);
								}
				} ]
			    
			});
		};
	});
	
</script>
<div id="admin_spgl_layout" class="easyui-layout" data-options="border:false,fit:true">
<div region="north" data-options="border:false,title:'设置相关信息'" style="height:100px;overflow:hidden;">
<form id="cashier_head"  method="post" style="padding:15px 0px;overflow: hidden;">
  <fieldset>
    <legend>会员信息及收银员</legend>
    销售单号：<input name="tid" readonly class="easyui-textbox" style="width:150px"/>
    会员卡卡号：<input name="cardid" readonly class="easyui-textbox" style="width:150px"/>
    会员姓名：<input name="name" readonly class="easyui-textbox"  style="width:150px"/>
    会员积分: <input name="integration" readonly class="easyui-textbox"  style="width:150px"/>
    收银员: <input name="cashier" readonly value="<%=sessionInfo.getUser().getLogname()%>" class="easyui-textbox"  style="width:150px"/>
  </fieldset>
</form>
</div>
<div region="center" data-options="border:false">
<table id="admin_cashier_datagrid"></table>
</div>
<div region="south"  data-options="border:false">
<div style="float:left;">
<form id="admin_cashier_searchForm" method="post" style="padding:5px 0px;">
<fieldset style="width:370px;height:110px;">
    <legend>输入框</legend>
    <h4>商品条形码编号(Enter键商品录入,录入框为空时→键进入结算)</h4>
    <label style="font-size:35px;">录入框：</label>
<input class="easyui-validatebox" name="foodid" style="width:180px;height:48px;font-size:35px;"/>
<!-- <a id="btn" href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add'" onclick="searchFun();" style="width:100px;height:50px;"><h3>回车结算</h3></a> -->
</fieldset>
</form>
</div>
<div style="float :left;">
<form id="cashier_sum"  method="post" style="padding:5px 0px;overflow: hidden;">
  <fieldset style="width:410px;height:110px;">
    <legend>合计</legend>
    <table>
    <tr><th><label style="font-size:18px;">合计金额：</label></th><td><input name="totalsum"  readonly style="width:80px;height:30px; font-size:20px;font-weight:bold;border-style:none; "/></td><th><label style="font-size:18px;">合计数量：</label></th><td><input name="totalnum"  readonly style="width:80px;height:23px;font-size:25px;font-weight:bold;border-style:none;"/></td></tr>
    <tr><th><label style="font-size:18px;">折扣：</label></th><td><input name="discount"  readonly style="width:50px;height:30px; font-size:20px;font-weight:bold;border-style:none; "/></td><th><label style="font-size:18px;">应收金额：</label></th><td><input name="receivable"  readonly style="width:120px;height:33px; font-size:38px;font-weight:bold;border-style:none; "/></td></tr>
    </table>
  </fieldset>
</form>
</div>
<div style="float :right;">
<form id="cashier_button"  method="post" style="padding:5px 0px;overflow: hidden;">
  <fieldset style="width:280px;height:110px;">
    <legend>功能键</legend>
   <a id="btn1"  class="easyui-linkbutton" data-options="" onclick="good();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#aad7ff;">查找商品</a>
   <a id="btn2"  class="easyui-linkbutton" data-options="" onclick="customer();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#ff96d7;">录入会员</a>
   <a id="btn3"  class="easyui-linkbutton" data-options="" onclick="outputReceipt();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#ffd7aa;">补打小票</a><br/>
   <a id="btn4"  class="easyui-linkbutton" data-options="" onclick="customer_add();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#ffd7aa;">新增会员</a>
   <a id="btn5"  class="easyui-linkbutton" data-options="" onclick="add();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#aad7ff;">数量+1</a>
   <a id="btn6"  class="easyui-linkbutton" data-options="" onclick="del();"style="width :80px;height:50px;margin:1px 2px;font-weight:bold;background :#ff96d7;">数量-1</a>
  </fieldset>
</form>
</div>
</div>
</div>